<template>
  <div v-loading="isStart">
<!--    <div class="no_config" v-if="setList.length == 0">-->
<!--    </div>-->
    <div class="my_page">
      <el-row :gutter="20">
        <el-col :span="6" v-for="(item, index) in setList" :key="index">
          <div class="my_card flex-column w-100 bg-white shadow">
            <div class="top p-10 d-flex justify-content-between">
              <div class="d-flex align-items-center">{{ item.deviceCode }}</div>
              <div>
                <el-button v-if="item.btnInfo.isControlShow=='show'" size="mini" round plain type="primary" @click="handlerOpenControl(item)">指令控制</el-button>
<!--                <el-button size="mini" round plain type="primary" @click="hanldeMake('close',item)">分闸</el-button>-->
                <el-button size="mini" round plain type="primary" @click="hanldeControl(item)">控制记录</el-button>
              </div>
            </div>
            <div class="d-flex w-100 dashed py-3">
              <div class="w-40 center">
                <img :src="item.devicePic" alt="" class="decive_img"/>
              </div>
              <div class="flex-column w-60 mt-2" @mousemove="getDetail(index)" @mouseleave="getDetail(null)">
                <div class="info">
                  <div class="d-flex">
                    <div class="line"></div>
                    设备状态信息
                  </div>
                  <div class="detail" v-show="detailIndex == index">
                    <div class="d-flex" v-for="(iten, indey) in item.paramList"
                         :key="indey">
                      <div class="titile">{{ iten.name }}：</div>
                      <span>{{ iten.value }}</span>
                    </div>
                  </div>
                </div>
                <div class="tab w-100 h-100">
                  <el-row>
                    <el-col :span="12" v-for="(iten, indey) in item.paramList"
                            :key="indey">
                      <div class="titile">{{ iten.name }}：{{ iten.value }}</div>
                    </el-col>
                  </el-row>
                </div>

              </div>
            </div>
            <el-row class="pl-2 pr-2" :gutter="10">
              <el-col :span="12">
                <div class="d-flex">
                  <div class="dot"></div>
                  <div class="titile">{{ item.deviceName }}</div>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="d-flex">
                  <div class="dot"></div>
                  <el-tooltip class="item" effect="dark" :content="item.deviceOfRegionSysName" placement="top">
                    <div class="titile">{{ item.deviceOfRegionSysName }}</div>
                  </el-tooltip>
                </div>
              </el-col>
            </el-row>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 弹框 -->
    <yc-dialog ref="ycSmsDialog" dialogTitle="短信验证码" dialogWidth="30%" :showCenter="false">
      <template #content>
        <el-row class="d-flex justify-content-center" v-loading="loading">
          <el-col :span="16">
            <el-input v-model="yzm" placeholder="请输入验证码"></el-input>
          </el-col>
          <el-col :span="8" class="d-flex align-items-center justify-content-center">
            <el-button type="primary" :disabled="disabled" @click="getCode()">{{title}}</el-button>
          </el-col>
        </el-row>
      </template>
      <template #footer>
        <el-button type="primary" @click="selectParamsSave">保存</el-button>
        <el-button @click="$refs.ycSmsDialog.dialogVisible = false">取消</el-button>
      </template>
    </yc-dialog>

    <!-- 指令控制 -->
    <yc-dialog ref="controlDialog" dialogTitle="指令控制" :showCenter="false">
      <template #content>
        <div class="w-100 h-100" v-loading="loading">
          <div class="mb-3" v-for="(item,index) in controlDataList" :key="index">
            <div class="mb-3 font-16 font-weight-bold ml-1">{{item.name}}</div>
            <div class="d-flex flex-wrap">
              <div class="mr-2 ml-1 mb-3" v-for="(itemY,indexY) in item.list" :key="indexY" @click="editControl(itemY)">
                <el-button size="small" plain type="primary">{{itemY.commandName}}</el-button>
              </div>
            </div>
          </div>
        </div>
      </template>
      <template #footer>
        <el-button @click="$refs.controlDialog.dialogVisible = false">取消</el-button>
      </template>
    </yc-dialog>

    <!-- 弹框 -->
    <yc-dialog ref="controlDialog1" dialogTitle="控制记录" :showCenter="false">
      <template #content>
        <div style="height: 500px;">
          <div class="pagination">
            <el-button type="success" size="small" @click="refresh" class="mb-2">刷新</el-button>
          </div>

          <common-table :tableHeight="'calc(100% - 80px)'" v-loading="tableLoading" show-index show-check-box
                        :columns="columns" :list="tableList" size="small">
          </common-table>
          <pagination class="pagination" :total="count" :page.sync="page.pageIndex" :limit.sync="page.pageSize"
                      @pagination="pagination"/>
        </div>
      </template>
      <template #footer>
        <el-button @click="$refs.controlDialog1.dialogVisible = false">取消</el-button>
      </template>
    </yc-dialog>
  </div>
</template>

<script>
  import ycDialog from "@/components/pageDialog"
  import CommonTable from "@/components/newSystem/newTable/CommonTable.vue"
  import { queryDeviceCenterConfig, queryDeviceCenterOne } from "@/api/settingManagement/kanbanManagement"
  import {
    getSmsCode, makeDeviceControl, makeDeviceControlSms,
    makeDeviceOpOrClose,
    makeDeviceOpOrCloseSms, queryControlList,
    queryDeviceDoPage,
    queryIsShowButton
  } from "@/api/showManage"

  export default {
    components: {
      ycDialog,
      CommonTable
    },
    data() {
      return {
        list: [],
        setList: [],
        isStart: true,
        detailIndex: null,
        timeInterval: null,
        testList: [],

        dataItem: {},
        disabled: false, //是否禁用按钮
        timer: null, //计时器
        second: "", //倒计时
        // smsData: "",
        yzmType: "",
        yzmCode: "",
        yzm: "",
        childRenList: [],

        tableLoading: false,
        columns: [
          {
            title: "指令流水号",
            prop: "sendCode",
            align: "center"
          }, {
            title: "控制名称",
            prop: "parameterName",
            align: "center"
          },{
            title: "指令名称",
            prop: "commandName",
            align: "center"
          },
          {
            title: "控制状态",
            prop: "controlState",
            align: "center",
            render: (h, params) => {
              if (params.row.controlState && params.row.controlState == "1") {
                return h("div", [h("el-tag", { props: { type: "success" } }, "指令发送成功")])
              } else if (params.row.controlState && params.row.controlState == "2") {
                return h("div", [h("el-tag", { props: { type: "" } }, "指令发送成功等待核验")])
              } else if (params.row.controlState && params.row.controlState == "3") {
                return h("div", [h("el-tag", { props: { type: "success" } }, "操作成功")])
              } else if (params.row.controlState && params.row.controlState == "4") {
                return h("div", [h("el-tag", { props: { type: "warning" } }, "操作失败核验超时")])
              } else {
                return h("div", [h("el-tag", { props: { type: "danger" } }, "故障分闸")])
              }
            }
          },
          {
            title: " 操作人",
            prop: "operatorName",
            align: "center"
          },
          {
            title: " 操作人类型",
            prop: "operatorType",
            align: "center",
            render: (h, params) => {
              if (params.row.operatorType && params.row.operatorType == "person") {
                return h("div", "人为")
              } else {
                return h("div", "工作流")
              }
            }
          },
          {
            title: " 下发时间",
            prop: "createTime",
            align: "center"
          },
        ],
        tableList: [],
        page: {
          pageSize: 10,
          pageIndex: 1
        },
        count: 0,

        loading: false,
        controlDataList: [],
        controlObj: {},
      }
    },
    computed: {
      title() {
        return this.disabled ? `重新获取（${this.second}）` : "获取验证码"
      }
    },
    created() {
      this.setTime()
      this.getSet()
    },
    beforeDestroy() {
      clearInterval(this.timeInterval)
      this.timeInterval = null
    },
    methods: {
      setTime() {
        this.timeInterval = setInterval(() => {
          this.getInfo()
        }, 5000)
      },

      async getSet() {
        this.setList = []
        await queryDeviceCenterConfig().then(res => {
          this.setList = res.object
          this.getInfo2()
          this.getInfo()
        })
      },

      async getInfo() {
        this.list = []
        // this.isStart = true
        for (let i = 0; i < this.setList.length; i++) {
          await queryDeviceCenterOne({
            deviceCode: this.setList[i].deviceCode,
            params: this.setList[i].params
          }).then(res => {
            if (res.object != null) {
              // this.setList[i].paramList = res.object.realData
              this.$set(this.setList[i], "paramList", res.object.realData)
            }
          })
        }
        this.isStart = false
      },
      async getInfo2() {
        for (let i = 0; i < this.setList.length; i++) {
          await queryIsShowButton({
            deviceCode: this.setList[i].deviceCode
          }).then(res => {
            if (res.status == 200) {
              this.$set(this.setList[i], "btnInfo", res.object)
            }
          })
        }
      },


      handlerOpenControl(data) {
        this.dataItem = data
        this.queryControlList()
        this.$refs.controlDialog.dialogVisible = true
      },

      async queryControlList() {
        this.loading = true
        const { object } = await queryControlList({
          deviceCode: this.dataItem.deviceCode
        })
        this.controlDataList = object
        this.loading = false
      },

      editControl(data) {
        this.controlObj = JSON.parse(JSON.stringify(data))
        this.$confirm("确定执行此指令吗, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          if (this.dataItem.btnInfo.isSms == "need") {
            this.yzm = ""
            clearInterval(this.timer)
            this.disabled = false
            this.$refs.ycSmsDialog.dialogVisible = true
          } else {
            this.loading = true
            makeDeviceControl({
              deviceCode: this.dataItem.deviceCode,
              parameterCode: data.parameterCode,
              command: data.command,
              commandName: data.commandName,
            }).then(res => {
              if (res.status == 200 && (res.message == '指令发送成功' || res.message == '指令发送成功等待核验')) {
                this.$message({
                  type: "success",
                  message: res.message
                })
                this.loading = false
              } else {
                this.$message({
                  type: "error",
                  message: res.message
                })
                this.loading = false
              }
            })
          }
        }).catch(() => {
          this.$message({
            type: "info",
            message: "已取消"
          })
        })
      },

      //获取短信验证码
      getCode() {
        let that = this
        getSmsCode({
          deviceCode: that.dataItem.deviceCode
        }).then(res => {
          if (res.status == 200) {
            this.$message({
              type: "success",
              message: res.message
            })
            this.yzmCode = res.object
          }
        })
        let s = 59  //倒计时间
        // if (!that.timer) {
        that.second = s
        that.disabled = true
        that.timer = setInterval(() => {
          if (that.second > 0 && this.second <= s) {
            that.second--
          } else {
            that.disabled = false
            clearInterval(that.timer)
            this.timer = null
          }
        }, 1000)
        // }
      },
      selectParamsSave() {
        this.loading = true
        this.addOrUpdateLoading = true
        makeDeviceControlSms({
          deviceCode: this.dataItem.deviceCode,
          parameterCode: this.controlObj.parameterCode,
          command: this.controlObj.command,
          commandName: this.controlObj.commandName,
          yzm: this.yzm,
          yzmCode: this.yzmCode
        }).then(res => {
          if (res.status == 200) {
            if (res.message == '指令发送成功' || res.message == '指令发送成功等待核验') {
              this.$message({
                type: "success",
                message: res.message
              })
              this.$refs.ycSmsDialog.dialogVisible = false
            } else {
              this.$message({
                type: "error",
                message: res.message
              })
            }
          } else {
            this.disabled = false
            clearInterval(this.timer)
            this.timer = null
          }
        })
        this.loading = false
        this.addOrUpdateLoading = false
      },


      // async hanldeMake(type, data) {
      //   this.dataItem = data
      //   if (data.isSms == "no") {
      //     const { status, success, object, message } = await makeDeviceOpOrClose({
      //       deviceCode: data.deviceCode,
      //       type
      //     })
      //     if (status == 200) {
      //       this.$message({
      //         type: "success",
      //         message: message
      //       })
      //     }
      //   } else {
      //     this.yzmType = type
      //     this.yzm = ""
      //     clearInterval(this.timer)
      //     this.disabled = false
      //     this.$refs.ycSmsDialog.dialogVisible = true
      //   }
      //
      // },
      //获取短信验证码
      // getCode() {
      //   let that = this
      //   getSmsCode({
      //     deviceCode: that.dataItem.deviceCode
      //   }).then(res => {
      //     if (res.status == 200) {
      //       this.yzmCode = res.object
      //     }
      //   })
      //   let s = 59  //倒计时间
      //   // if (!that.timer) {
      //   that.second = s
      //   that.disabled = true
      //   that.timer = setInterval(() => {
      //     if (that.second > 0 && this.second <= s) {
      //       that.second--
      //     } else {
      //       that.disabled = false
      //       clearInterval(that.timer)
      //       this.timer = null
      //     }
      //   }, 1000)
      //   // }
      // },
      // selectParamsSave() {
      //   makeDeviceOpOrCloseSms({
      //     deviceCode: this.dataItem.deviceCode,
      //     type: this.yzmType,
      //     yzm: this.yzm,
      //     yzmCode: this.yzmCode
      //   }).then(res => {
      //     if (res.status == 200) {
      //       this.$message({
      //         type: "success",
      //         message: res.message
      //       })
      //       this.$refs.ycSmsDialog.dialogVisible = false
      //     }
      //   })
      // },

      async hanldeControl(data) {
        this.dataItem = data
        await this.getListData()
        this.$refs.controlDialog1.dialogVisible = true
      },
      async getListData() {
        this.tableLoading = true
        const { status, success, object, message } = await queryDeviceDoPage({
          ...this.page,
          deviceCode: this.dataItem.deviceCode,
          sendType: 'control'
        })
        if (status == 200) {
          this.count = object.count
          this.tableList = object.data
        }
        this.tableLoading = false
      },
      pagination(pageItem) {
        this.getListData(pageItem.page, pageItem.limit)
      },

      refresh() {
        this.getListData()
      },

      getDetail(i) {
        this.detailIndex = i
      }
    }
  }
</script>
<style lang="scss" scoped>
  .pagination {
    display: flex;
    justify-content: flex-end;
  }

  .no_config {
    width: 100%;
    height: calc(100vh - 50px);
    background-image: url('../../../../assets/img/no_config.png');
    background-repeat: no-repeat;
    background-size: 100% 100%;
    -moz-background-size: 100% 100%;
  }

  .top {
    // background-color: #dfeffe;
    position: relative;
    border-top-left-radius: 12px !important;
    border-top-right-radius: 12px !important;
    background: linear-gradient(to right, #d7ebfd, #e8f4ff);

  }

  .info {
    display: flex;
    height: 20px;
    position: relative;
    justify-content: space-between;
  }

  .my_card {
    height: 270px;
    cursor: pointer;
    border-radius: 12px !important;
  }

  .detail {
    position: absolute;
    top: 20px;
    // left: -100px;
    right: 0;
    width: 380px;
    max-height: 140px;
    overflow-y: auto;
    opacity: 0.95;
    z-index: 199;
    background-color: #f5f5f6;
    border-radius: 8px;
    padding: 18px 18px 8px 18px;
    display: flex;
    flex-wrap: wrap;

    .d-flex {
      margin-right: 20px;
      margin-bottom: 10px;
    }
  }

  .omit {
    color: #3276ff;
    font-size: 28px;
    margin-right: 12px;
    margin-bottom: 32px;
  }

  .mange {
    position: absolute;
    right: 0;
    top: 0;
    width: 50px;
    height: 100%;
    // font-size: 16px;
    color: #fff;
    background-color: #4c88ff;
    border-top-right-radius: 12px !important;
    border-bottom-left-radius: 12px !important;
  }

  .d-flex {
    display: flex;
  }


  .my_page {
    display: flex;
    flex-direction: column;
    height: calc(100vh - 50px);
    overflow-y: auto;
    padding: 8px 20px 20px;

    .el-row {
      display: flex;
      flex-flow: row wrap;
    }

    .el-col {
      margin-top: 12px;
    }

    .el-card {
      height: 270px;
      border-radius: 12px;
      cursor: pointer;
      overflow-y: auto;
    }

    .el-card:hover {
      border: 1px solid #65a0fa;
    }

    .el-card ::v-deep .el-card__body {
      padding: 0 !important;
      // overflow: visible !important;
    }
  }

  .center {
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .my_img {
    height: 60px;
    width: 60px;
  }

  .text-center {
    text-align: center;
  }

  .flex-column {
    display: flex;
    flex-direction: column;
  }

  .p-3 {
    padding: 12px;
  }

  .decive_img {
    width: 70%;
    object-fit: contain;
    background-color: #e7e7e7;
    border-radius: 8px;
  }

  .w-100 {
    width: 100%;
  }

  .w-50 {
    width: 50%;
  }

  .w-40 {
    width: 40%;
  }

  .w-60 {
    width: 60%;
  }

  .titile {
    // white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    -o-text-overflow: ellipsis;
    white-space: nowrap;
    display: block;

    // font-size: 14px;
    // font-weight: 400;
    // min-width: 70px;
  }

  .tab {
    // display: flex;
    // flex-wrap: wrap;
    // align-content: flex-start;
    height: 120px;
    overflow-y: auto;
    // margin: 10px 0 0 0;
  }

  .col_tab {
    height: 80px;
    overflow-y: auto;
  }

  .mb-3 {
    margin-bottom: 12px;
  }

  .mt-3 {
    margin-top: 12px;
  }

  ::-webkit-scrollbar {
    width: 4px;
    height: 6px;
  }

  ::-webkit-scrollbar-track {
    border-radius: 4px;
  }

  ::-webkit-scrollbar-thumb {
    border-radius: 8px;
    background-color: #DDDEE0;
  }

  ::-webkit-scrollbar-thumb:hover {
    background-color: #C7C9CC;
  }

  .text-success {
    color: #17c56a;
  }

  .text-open {
    color: #97a1fd;
  }

  .line {
    width: 4px;
    height: 12px;
    background-color: #3276ff;
    margin-right: 10px;
    border-radius: 4px;
  }

  .dashed {
    border-bottom: 1px dashed #dcdcdc;
  }

  .dot {
    width: 8px;
    height: 8px;
    border-radius: 50%;
    margin-right: 6px;
    margin-top: 4px;
    background-color: #d6ecff;
  }

  .p-10 {
    padding: 12px;
  }
</style>
